<template>
  <div class="payment-container">
    <div class="payment-card">
      <!-- 支付头部 -->
      <div class="payment-header">
        <h2>订单支付</h2>
        <p class="order-info">订单号：{{ orderNo }}</p>
      </div>

      <!-- 支付金额 -->
      <div class="payment-amount">
        <div class="amount-label">支付金额</div>
        <div class="amount-value">¥{{ formatPrice(totalAmount) }}</div>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <div class="method-title">选择支付方式</div>
        <div class="method-list">
          <div
              v-for="method in paymentMethods"
              :key="method.id"
              :class="{ active: selectedMethod === method.id }"
              class="method-item"
              @click="selectedMethod = method.id"
          >
            <div class="method-icon">
              <el-icon :size="24">
                <component :is="method.icon"/>
              </el-icon>
            </div>
            <div class="method-info">
              <div class="method-name">{{ method.name }}</div>
              <div class="method-desc">{{ method.desc }}</div>
            </div>
            <div class="method-radio">
              <el-radio v-model="selectedMethod" :value="method.id"/>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付按钮 -->
      <div class="payment-actions">
        <el-button size="large" @click="goBack">取消支付</el-button>
        <el-button
            :loading="paying"
            size="large"
            type="primary"
            @click="handlePayment"
        >
          确认支付 ¥{{ formatPrice(totalAmount) }}
        </el-button>
      </div>
    </div>

    <!-- 支付成功对话框 -->
    <el-dialog v-model="showSuccessDialog" :show-close="false" title="支付成功" width="400px">
      <div class="success-content">
        <el-icon :size="60" class="success-icon" color="#67C23A">
          <SuccessFilled/>
        </el-icon>
        <h3>支付成功！</h3>
        <p>订单号：{{ orderNo }}</p>
        <p>支付金额：¥{{ formatPrice(totalAmount) }}</p>
      </div>
      <template #footer>
        <el-button @click="goToOrderDetail">查看订单详情</el-button>
        <el-button type="primary" @click="goToHome">继续购物</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {CreditCard, SuccessFilled, Wallet} from '@element-plus/icons-vue'
import {payOrder as payOrderApi} from '@/api/order'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const orderId = ref(null)
const orderNo = ref('')
const totalAmount = ref(0)
const selectedMethod = ref(1)
const paying = ref(false)
const showSuccessDialog = ref(false)
const currentOrderId = ref(null)

// 支付方式列表
const paymentMethods = ref([
  {
    id: 1,
    name: '微信支付',
    desc: '使用微信扫码支付',
    icon: CreditCard
  },
  {
    id: 2,
    name: '支付宝支付',
    desc: '使用支付宝扫码支付',
    icon: Wallet
  }
])

// 页面初始化
onMounted(() => {
  // 从路由参数获取订单信息
  orderId.value = route.params.orderId
  orderNo.value = route.query.orderNo || ''
  totalAmount.value = parseFloat(route.query.totalAmount || 0)

  if (!orderId.value) {
    ElMessage.error('订单信息错误')
    router.push('/order')
  }
})

// 处理支付
const handlePayment = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要支付 ¥${formatPrice(totalAmount.value)} 吗？`,
        '确认支付',
        {
          confirmButtonText: '确定支付',
          cancelButtonText: '取消',
          type: 'info'
        }
    )

    paying.value = true

    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 调用支付API
    await payOrderApi(orderId.value)

    // 设置当前订单ID并显示支付成功对话框
    currentOrderId.value = orderId.value
    showSuccessDialog.value = true

  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error(error.response?.data?.message || '支付失败')
    }
  } finally {
    paying.value = false
  }
}

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return '0.00'
  }
  return parseFloat(price).toFixed(2)
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到订单详情
const goToOrderDetail = () => {
  showSuccessDialog.value = false
  // 跳转到当前订单的详情页面
  router.push(`/order/${currentOrderId.value}`)
}

// 跳转到首页
const goToHome = () => {
  showSuccessDialog.value = false
  router.push('/')
}
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.payment-card {
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  padding: 2.5rem;
  box-shadow: var(--shadow-xl);
  width: 100%;
  max-width: 500px;
  border: 1px solid var(--border-light);
}

.payment-header {
  text-align: center;
  margin-bottom: 30px;
}

.payment-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.order-info {
  color: #666;
  margin: 0;
}

.payment-amount {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.amount-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.amount-value {
  color: #e74c3c;
  font-size: 32px;
  font-weight: bold;
}

.payment-methods {
  margin-bottom: 40px;
}

.method-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.method-item:hover {
  border-color: #409eff;
}

.method-item.active {
  border-color: #409eff;
  background: #f0f8ff;
}

.method-icon {
  margin-right: 12px;
  color: #409eff;
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.method-desc {
  color: #666;
  font-size: 12px;
}

.payment-actions {
  display: flex;
  gap: 16px;
}

.payment-actions .el-button {
  flex: 1;
  height: 48px;
  font-size: 16px;
}

.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  margin-bottom: 16px;
}

.success-content h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.success-content p {
  margin: 8px 0;
  color: #666;
}
</style>
